import java.sql.Time;
import java.util.Comparator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Lock;

public class Demo {
    public static void main(String[] args) {
        My_Timer my_timer = new My_Timer();
        System.out.println("haha");
        my_timer.schedule(new MyTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("task1");
            }
        },100));
        my_timer.schedule(new MyTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("task1");
            }
        },200));
        my_timer.schedule(new MyTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("task1");
            }
        },300));


    }
}
class Locker{

}
class My_Timer {
    private PriorityBlockingQueue<MyTask> tasks = new PriorityBlockingQueue();
    private Locker locker = new Locker();
    public void schedule(MyTask myTask) {
        synchronized (locker) {
            tasks.put(myTask);
            locker.notify();
        }

    }
    public My_Timer() {
        Thread work = new Thread(()->{
           while (true) {
               synchronized (locker) {
                   System.out.println("hehe");
                   try {
                       MyTask task = tasks.take();
                       long cur = System.currentTimeMillis();
                       System.out.println("1111");
                       if (task.delay < cur) {
                           task.task.run();
                           System.out.println("222");
                       } else {
                           tasks.put(task);
                           locker.wait(task.delay  - cur );
                           System.out.println("3333");
                       }
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   System.out.println("heihei");

               }
           }
        });
        work.start();
    }



}
class MyTask implements Comparable<MyTask> {

    public long delay ;
    public Runnable task;

    public MyTask(Runnable task ,long delay) {
        this.delay = System.currentTimeMillis() + delay;
        this.task = task;
    }
    @Override
    public int compareTo(MyTask o) {
        return (int)(this.delay - o.delay);
    }
}